<?php
namespace trading\service;

use herosphp\core\Loader;
use herosphp\bean\Beans;

class CartService extends CommonService{

    private $productService = null;
    private $cartModel = null;
    private $cartProductModel = null;
    private $cartProductService = null;

    public function __construct($model){
        parent::__construct($model);
        $this->cartModel = Loader::model($model);
        $this->productService = Beans::get('product.product.service');
        $this->cartProductModel = Loader::model('tradingCartProduct');
        $this->cartProductService = Beans::get('trading.tradingCartProduct.service');
    }

    /**
     * 加入购物车
     * @param $member_id 用户id
     * @param $id 产品id
     * @return int
     */
    public function addCartProduct($member_id,$id){
        $item = $this->cartModel->getItem(array('member_id'=>$member_id));
        if(!$item){
            $cart_id = $this->cartModel->add(array('member_id'=>$member_id));
        }else{
            $cart_id = $item['id'];

        }
        $product_items = $this->productService->getProductsByIds(array($id),$member_id);
        if(!$product_items) return -1;//没有此产品
        $data = array(
            'cart_id'=>$cart_id,
            'product_id'=>$id
        );
        if(!$this->cartProductModel->getItem($data)){
            return $this->cartProductModel->add($data);
        }else{//购物车已存在此产品
            return -2;
        }
    }

    /**
     * 获取购物车产品
     * @param $member_id
     * @return array|mixed|null
     */
    public function getCarts($member_id){
        $item = $this->cartModel->getItem(array('member_id'=>$member_id));
        if(!$item){
            $this->cartModel->add(array('member_id'=>$member_id));
            return NULL;
        }

        $products_data = $this->cartProductModel->getItems(array('cart_id'=>$item['id']));
        $productIds = array();
        foreach($products_data as $v){
            $productIds[] = $v['product_id'];
        }
        if(empty($productIds)) return array();
        $product_items = $this->productService->getProductsByIds($productIds,$member_id);
        $arr = array();
        foreach($product_items as $k=>$v){
            $arr[$k]['name'] = $v['type_name'].'/'.$v['product_name'].'/'.$v['factory_name'].'/'.$v['brand_name'].'<br/>货品规格(KG/袋)：'.$v['pkg_size'];
            $arr[$k]['delivery_way'] = $v['delivery_way'];
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['product_no'] = $v['product_no'];
            $arr[$k]['repertory_id'] = $v['repertory_id'];
            $arr[$k]['sales_price'] = setFloat($v['sales_price'],2);
            $arr[$k]['min_volume'] = setFloat($v['min_volume'],3);
            $arr[$k]['max_volume'] = setFloat($v['quantity']-$v['freeze_quantity'],3);
            $arr[$k]['quantity'] = setFloat($v['quantity']-$v['freeze_quantity'],3);
            $arr[$k]['has'] = $v['quantity']-$v['freeze_quantity']-$v['min_volume'];
            $arr[$k]['price'] = bcmul($v['min_volume'],$v['sales_price'],2);
            $arr[$k]['deliveryway'] = $this->productService->getDeliveryWayText($v['delivery_way']);
            $arr[$k]['address'] = $v['address'];
        }
        $item['product'] = $arr;
        $item['productIdArr'] = $productIds;
        return $item;
    }

    /**
     * 根据cookie获取产品信息
     * @param $data
     * @return mixed
     */
    public function getCookieProduct($data){
        /*$productIds = array();
        foreach($data as $v){
            $productIds[] = $v['product_id'];
        }*/
        $product_items = $this->productService->getProductsByIds($data);
        $arr = array();
        foreach($product_items as $k=>$v){
            $arr[$k]['name'] = $v['type_name'].'/'.$v['product_name'].'/'.$v['factory_name'].'/'.$v['brand_name'].'<br/>货品规格(KG/袋)：'.$v['pkg_size'];
            $arr[$k]['delivery_way'] = $v['delivery_way'];
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['product_no'] = $v['product_no'];
            $arr[$k]['repertory_id'] = $v['repertory_id'];
            $arr[$k]['sales_price'] = setFloat($v['sales_price'],2);
            $arr[$k]['min_volume'] = setFloat($v['min_volume'],3);
            $arr[$k]['max_volume'] = setFloat($v['quantity']-$v['freeze_quantity'],3);
            $arr[$k]['quantity'] = setFloat($v['quantity']-$v['freeze_quantity'],3);
            $arr[$k]['has'] = $v['quantity']-$v['freeze_quantity']-$v['min_volume'];
            $arr[$k]['price'] = bcmul($v['min_volume'],$v['sales_price'],2);
            $arr[$k]['deliveryway'] = $this->productService->getDeliveryWayText($v['delivery_way']);
            $arr[$k]['address'] = $v['address'];
        }
        $item['product'] = $arr;
        return $item;
    }

    /**
     * 提交购物车产品
     * @param $ids 产品id组
     * @param $quantity 产品数量组
     * @param $member_id 用户id
     * @return bool
     */
    public function createOrder($member_id,$ids,$quantity){
        if(!$ids || !$quantity || !$member_id) return false;
        $productModel = Loader::model('product');
        $product_items = $this->productService->getProductsByIds($ids,$member_id);
        if(!$product_items) return false;
        $product_arr = array();
        $repertory_id = 0;
        $delivery_way = 0;
        foreach($product_items as $k=>$v){
            if($k == 0){
                $repertory_id = $v['repertory_id'];
                $delivery_way = $v['delivery_way'];
            }else{
                if($repertory_id != $v['repertory_id']){//产品不在同一个仓库里面
                    return -1;
                }
                if($delivery_way != $v['delivery_way']){//产品不是同一种交收方式
                    return -2;
                }
            }
            $product_arr[$v['id']] = $v;
        }
        $quantity_arr = array();
        foreach($ids as $k=>$v){
            $quantity_arr[$v] = $quantity[$k];
        }
        $arr = array();
        $total_prict = 0;
        $total_quantity = 0;
        foreach($product_arr as $k=>$v){
            if($v['app_id'] != appId()){
                return -3;//产品不属于运营商
            }
            $buy_min = bcsub($v['min_volume'],$quantity_arr[$k],3);
            $quantity = bcsub($v['quantity'],$v['freeze_quantity'],3);
            $buy_max = bcsub($quantity,$quantity_arr[$k],3);
            if($buy_min>0 || $buy_max<0){
                return -4;//购买数量不合法
            }
            $price = bcmul($quantity_arr[$k],$v['sales_price'],2);
            $total_prict += $price;
            $total_quantity += $quantity_arr[$k];
            $arr[$k]['name'] = $v['type_name'].'/'.$v['product_name'].'/'.$v['factory_name'].'/'.$v['brand_name'].'<br/>货品规格(KG/袋)：'.$v['pkg_size'];

            $arr[$k]['product_no'] = $v['product_no'];
            $arr[$k]['sales_price'] = setFloat($v['sales_price'],2);
            $arr[$k]['quantity'] = setFloat($v['quantity']-$v['freeze_quantity'],3);
            $arr[$k]['min_volume'] = setFloat($v['min_volume'],3);
            $arr[$k]['address'] = $v['address'];
            $arr[$k]['buy_quantity'] = setFloat($quantity_arr[$k],3);
            $arr[$k]['price'] = setFloat($price,2);

        }
        switch($product_items[0]['delivery_way']){
            case $productModel::SHIPPING_WAY_SELLER:
                $deliveryWay = '卖家配送';break;
            case $productModel::SHIPPING_WAY_BUYER:
                $deliveryWay = '买家自提';break;
        }
        $items['product'] = $arr;
        $items['deliveryWay'] = $deliveryWay;
        $items['delivery_way'] = $product_items[0]['delivery_way'];
        $items['total_prict'] = setFloat($total_prict,2);
        $items['total_quantity'] = setFloat($total_quantity,3);

        return $items;

    }

    /**
     * 删除单个购物车商品
     * @param $member_id 用户id
     * @param $id 产品id
     * @return bool
     */
    public function delCartProduct($member_id,$id){
        $item = $this->cartModel->getItem(array('member_id'=>$member_id));
        if(!$item) return false;

        return $this->cartProductModel->deletes(array('cart_id'=>$item['id'],'product_id'=>$id));
    }

    /**
     * 删除多个购物车商品
     * @param $member_id 用户iid
     * @param $data 产品id组
     * @return bool
     */
    public function delCartProducts($member_id,$data){
        $item = $this->cartModel->getItem(array('member_id'=>$member_id));
        if(!$item) return false;

        return $this->cartProductModel->deletes(array('cart_id'=>$item['id'],'product_id'=>array('$in'=>$data)));
    }



    /**
     * 内部调取API
     */

    /**
     * 购物车统计数量
     * @param $member_id 用户Id
     * @return int|string
     */
    public function CartProductTotal($member_id){
        $item = $this->cartModel->getItem(array('member_id'=>$member_id));
        if(!$item){
            $this->cartModel->add(array('member_id'=>$member_id));
            return '0';
        }
        $res = $this->cartProductModel->where(array('cart_id'=>$item['id']))->group('product_id')->field('id')->find();
        return $res?count($res):0;
    }
}

